
package org.apache.solr.cloud;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.Slice;

public class AssignShard {

    /**
     * Assign a new unique id up to slices count - then add replicas evenly.
     *
     * @return the assigned shard id
     */
    public static String assignShard(String collection, ClusterState state, Integer numShards) {

        if(numShards == null) {
            numShards = 1;
        }

        Map<String, Slice> sliceMap = state.getSlices(collection);

        if(sliceMap == null) {
            return "shard1";
        }

        List<String> shardIdNames = new ArrayList<>(sliceMap.keySet());

        if(shardIdNames.size() < numShards) {
            return "shard" + (shardIdNames.size() + 1);
        }

        // else figure out which shard needs more replicas
        final Map<String, Integer> map = new HashMap<>();
        for(String shardId : shardIdNames) {
            int cnt = sliceMap.get(shardId).getReplicasMap().size();
            map.put(shardId, cnt);
        }

        Collections.sort(shardIdNames, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                Integer one = map.get(o1);
                Integer two = map.get(o2);
                return one.compareTo(two);
            }
        });

        return shardIdNames.get(0);
    }
}
